package com.example.yunhailutong.zhongtan.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.yunhailutong.zhongtan.R;
import com.example.yunhailutong.zhongtan.app.App;
import com.example.yunhailutong.zhongtan.app.OldsEvent;
import com.example.yunhailutong.zhongtan.constant.Url;
import com.example.yunhailutong.zhongtan.entity.ChanPinFenLeiEntity;
import com.example.yunhailutong.zhongtan.entity.ImageEntity;
import com.example.yunhailutong.zhongtan.net.PersionBiz;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.squareup.picasso.Picasso;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import fj.dropdownmenu.lib.concat.DropdownI;
import fj.dropdownmenu.lib.pojo.DropdownItemObject;
import me.leefeng.promptlibrary.PromptButton;
import me.leefeng.promptlibrary.PromptButtonListener;
import me.leefeng.promptlibrary.PromptDialog;

/**
 * Created by yunhailutong on 2018/4/26.
 */

public class ActivityNewGongYing extends ActivityBase implements DropdownI.SingleRow {


    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.jiage)
    TextView jiage;
    @BindView(R.id.num)
    EditText num;
    @BindView(R.id.chanpinmingcheng)
    EditText chanpinmingcheng;
    @BindView(R.id.gongkaijiage)
    EditText gongkaijiage;
    @BindView(R.id.shangchuantupian)
    TextView shangchuantupian;
    @BindView(R.id.chanpinmiaoshu)
    EditText chanpinmiaoshu;
    @BindView(R.id.update_register)
    Button updateRegister;
    @BindView(R.id.image1)
    ImageView image1;
    @BindView(R.id.image2)
    ImageView image2;
    @BindView(R.id.image3)
    ImageView image3;
    @BindView(R.id.cailiao)
    TextView cailiao;

    private PromptDialog chanpinDialog;
    private ChanPinFenLeiEntity chanPinFenLeiEntity;
    private String cailiaoid = "";
    private String type = "";
    private String ImagePath = "";
    private int imagezhangshu = 0;
    private String imagetypes = "";

    @Override
    protected void addListener() {
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        cailiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (chanPinFenLeiEntity == null) {
                    disPlay("请等待材料列表加载完成");
                } else {
                    initChanPin(chanPinFenLeiEntity);
                }
            }
        });
    }

    @Override
    protected void initActivity(Bundle savedInstanceState) {
        ButterKnife.bind(this);
    }

    @Override
    protected int contentViewById() {
        return R.layout.activity_new_gongying;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        type = getIntent().getStringExtra("type");
        Map<String, String> params = new HashMap<>();
        new PersionBiz().GetChanPinFenLei(params);
        showWaitingDialog();
        if (type.equals("1")) {
            title.setText("发布供应信息");
            imagetypes = "supply";
            updateRegister.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (ImagePath.equals("")) {
                        disPlay("请先上传图片");
                    } else if (jiage.getText().toString().equals("")) {
                        disPlay("价格不能为空请选择");
                    } else if (num.getText().toString().equals("")) {
                        disPlay("数量不能为空");
                    } else if (chanpinmingcheng.getText().toString().equals("")) {
                        disPlay("产品名称不能为空");
                    } else if (chanpinmiaoshu.equals("")) {
                        disPlay("产品描述不能为空");
                    }  else if (cailiaoid.equals("")) {
                        disPlay("请先选择材料类别");
                    } else {
                        Map<String, String> params = new HashMap<>();
                        //   params.put("username", userNameRegister.getText().toString());
                        params.put("token", App.token);
                        params.put("title", chanpinmiaoshu.getText().toString());
                        params.put("content", chanpinmiaoshu.getText().toString());
                        params.put("imgpath", ImagePath);
                        params.put("num", num.getText().toString());
                        params.put("mmId", App.id);
                        params.put("sdType", cailiaoid);
                        new PersionBiz().addXuQiuGongYing(Url.NEWGONGYING, params);
                    }
                }
            });
        } else {
            title.setText("发布需求信息");
            imagetypes = "demand";
            updateRegister.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (ImagePath.equals("")) {
                        disPlay("请先上传图片");
                    } else if (jiage.getText().toString().equals("")) {
                        disPlay("价格不能为空请选择");
                    } else if (num.getText().toString().equals("")) {
                        disPlay("数量不能为空");
                    } else if (chanpinmingcheng.getText().toString().equals("")) {
                        disPlay("产品名称不能为空");
                    } else if (chanpinmiaoshu.getText().toString().equals("")) {
                        disPlay("产品描述不能为空");
                    }  else if (cailiaoid.equals("")) {
                        disPlay("请先选择材料类别");
                    } else {
                        Map<String, String> params = new HashMap<>();
                        //   params.put("username", userNameRegister.getText().toString());
                        params.put("token", App.token);
                        params.put("title", chanpinmiaoshu.getText().toString());
                        params.put("content", chanpinmiaoshu.getText().toString());
                        params.put("imgpath", ImagePath);
                        params.put("num", num.getText().toString());
                        params.put("mmId", App.id);
                        params.put("sdType", cailiaoid);

                        new PersionBiz().addXuQiuGongYing(Url.NEWQUXIU, params);
                    }
                }
            });
        }
        shangchuantupian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (imagezhangshu <= 2) {
                    PictureSelector.create(ActivityNewGongYing.this)
                            .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                            .maxSelectNum(1)// 最大图片选择数量 int
                            .minSelectNum(1)// 最小选择数量 int
                            .imageSpanCount(4)// 每行显示个数 int
                            .selectionMode(PictureConfig.SINGLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                            .previewImage(true)// 是否可预览图片 true or false
                            .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                            .forResult(188);//结果回调onActivityResult code
                } else {
                    disPlay("最多上传三张图片");
                }
            }
        });

    }

    private void initChanPin(final ChanPinFenLeiEntity entity) {
        chanpinDialog = new PromptDialog(this);

        //可创建android效果的底部Sheet选择，默认IOS效果，sheetCellPad=0为Android效果的Sheet
        //                promptDialog.getAlertDefaultBuilder().sheetCellPad(0).round(0);
        //设置按钮的特点，颜色大小什么的，具体看PromptButton的成员变量
        PromptButton cancle = new PromptButton("取消", null);
        cancle.setTextColor(Color.parseColor("#0076ff"));
        //设置显示的文字大小及颜色
        chanpinDialog.getAlertDefaultBuilder().textColor(Color.GRAY);

        int length;
        if (entity.getData().size() < 11) {
            length = entity.getData().size() + 1;
        } else {
            length = 12;
        }
        PromptButton[] lists = new PromptButton[length];
        for (int i = 0; i < length; i++) {
            if (i == 0) {
                lists[i] = cancle;
            } else {
                final int finalI = i;
                String name = entity.getData().get(i - 1).getName();
                lists[i] = new PromptButton(name, new PromptButtonListener() {
                    @Override
                    public void onClick(PromptButton button) {
                        cailiaoid = String.valueOf(entity.getData().get(finalI - 1).getId());
                        cailiao.setText(entity.getData().get(finalI - 1).getName());
                    }
                });
            }
        }
        chanpinDialog.showAlertSheet("", true, lists);
    }

    @Subscribe
    public void logs(OldsEvent.UpLoadImageEvent msg) {
        dismissWaitingDialog();
        if (msg.what == -1) {
            disPlay(msg.obj.toString());
        }
        if (msg.what == 1) {
            ImageEntity entity = (ImageEntity) msg.obj;
            if (imagezhangshu == 0) {
                ImagePath = ImagePath + entity.getFileNameList().get(0).getImgName();
                imagezhangshu = imagezhangshu + 1;
                final String image = entity.getFileNameList().get(0).getImgPath();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Picasso.with(mContext).load(image).into(image1);
                    }
                });

            } else if (imagezhangshu == 1) {
                imagezhangshu = imagezhangshu + 1;
                ImagePath = ImagePath + "," + entity.getFileNameList().get(0).getImgName();
                final String image = entity.getFileNameList().get(0).getImgPath();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Picasso.with(mContext).load(image).into(image2);
                    }
                });
            } else if (imagezhangshu == 2) {
                imagezhangshu = imagezhangshu + 1;
                ImagePath = ImagePath + "," + entity.getFileNameList().get(0).getImgName();
                final String image = entity.getFileNameList().get(0).getImgPath();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Picasso.with(mContext).load(image).into(image3);
                    }
                });
            }
        }
    }

    @Subscribe
    public void log(OldsEvent.UpGongYingXuQiuEvent msg) {
        dismissWaitingDialog();
        if (msg.what == -1) {
            disPlay(msg.obj.toString());
        }
        if (msg.what == 1) {
            disPlay("提交成功");
            finish();
        }
    }

    @Subscribe
    public void log(OldsEvent.ChanPinFenLeiEvent msg) {
        dismissWaitingDialog();
        if (msg.what == -1) {
            disPlay(msg.obj.toString());
        }
        if (msg.what == 1) {
            chanPinFenLeiEntity = (ChanPinFenLeiEntity) msg.obj;
        }
    }

    @Override
    public void onSingleChanged(DropdownItemObject dropdownItemObject) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 188:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    final File file1 = new File(selectList.get(0).getPath());
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            new PersionBiz().uploadImage("", imagetypes, file1);
                        }
                    }).start();
                    showWaitingDialog();
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    break;
            }
        }
    }
}
